/*-
 * Copyright (c) 2006 Vishal Patil <bsd.devil@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#include "iscsi_pdu.h"
#include "iscsi_session.h"
#include "iscsi_tools.h"
#include "iscsi_pdu_list.h"
#include "iscsi_login_params.h"

#define MAX_ISCSI_PDUS 256

char program[32];
const char * initiator_name = "iqn.2006-01.info.vishpat:";

/* Printed when a user provides wrong or no parameters */
void usage(char* message)
{
	if (message != NULL) {
		printf("Error: %s\n", message);
	}		
	printf("Usage: %s -h hostname [-p port]\n", program);
	exit (-1);
}

/*
 *	Initialize the login parameters for the discovery session
 */
int init_login_params(struct iscsi_login_params * params,
		char * host, int port) 
{
	if (!params) {
		return -1;
	}

	params->sessionType 			= "Discovery";
	params->targetAddress			= host;
	params->targetName			= 0;
	params->initiatorName			= (char *)initiator_name;
	params->authMethod			= "None";
	params->headerDigest			= "None";
	params->dataDigest			= "None";
	params->port				= port;
	params->maxConnections			= 1;
	params->maxRecvDataSegmentLength 	= 65536;
	params->maxBurstLength 			= 65536;
	params->firstBurstLength 		= 65536;
	params->defaultTime2Wait		= 0;
	params->defaultTime2Retain		= 0;
	params->maxOutstandingR2T		= 1;
	params->errorRecoveryLevel		= 0;
	params->dataPDUInOrder			= 1;
	params->dataSequenceInOrder		= 1;
	params->initialR2T			= 1;
	params->immediateData			= 1;	
	
	return 0;	
}


/*
 *	Get Targets
 */
int get_targets(char * host, int port) {
	struct iscsi_session sess;
	struct iscsi_login_params params;

	/* Initialize the DISCOVERY session */
	iscsi_session_init(&sess);

	/* Init the login parameters */
	init_login_params(&params,host,port);

	sess.login_params = &params;
	
	/* Create a TCP/IP connection to the network entity */	
	if (create_connection(&sess) == -1) {
		perror("Problem connecting to the network");
		return -1;
	}

	/* Try logging into the network entity */
	if (login(&sess) == -1) {
		perror("Problem logging into network entity");
		return -1;
	}

	/* Send the SendTargets text command */	
	if (sess.state == ISCSI_SESS_LOGGED_IN && 
					sendtargets(&sess) == -1) {
		perror("Problem will sending the SendTargets command");
		return -1;
	}
	
	/* Try logging into the network entity */
	if (logout(&sess) == -1) {
		perror("Problem logging out of network entity");
		return -1;
	}
			
	/* Close the TCP/IP connection to the network entity */	
	if (close_connection(&sess) == -1) {
		perror("Proble closing the connection to network entity");
	}
	return 0;
}
/*
 *	Discovers the targets on a network entity using hostname and port
 */
int 
main(int argc, char **argv ) {
	int ch;
	char * host = NULL;
	int port = -1;

	memcpy(program,argv[0],strlen(argv[0]) + 1);

	while ((ch = getopt(argc,argv,"h:p:")) != EOF) {
		switch (ch) {
			case 'h':
				host = optarg;
				break;
			case 'p':
				port = strtol(optarg,NULL,10);
				if (!port) {
					usage("Invalid port");
				}					
				break;			
		}	
	}	

	argc -= optind;
	argv += optind;	

	if (host == NULL) {
		usage("You must specific a host with -h option");	
	}		

	if (port == -1) {
		port = ISCSI_PORT;
	}		

	/* Initialize the PDU list */	
	iscsi_pdu_list_init(MAX_ISCSI_PDUS);

	/* This is the main function doing the all of the work */	
	get_targets(host,port);

	/* Destroy the PDU list */
	iscsi_pdu_list_destroy();
	
	return 0;
}

